package info.fernandoguillen.javadb2;

import java.util.List;

import info.fernandoguillen.javadb2.persistence.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;


/**
 * <p>
 * </p>
 * 
 * @internal_author fguillen.mail@gmail.com
 * @date 18/04/2008
 *
 */
public class MessageManager {
	private static final Logger log = 
		Logger.getLogger( MessageManager.class );
	
	/**
	 * <p>
	 * 
	 * </p>
	 * @date: 18/04/2008
	 * @author: fguillen.mail@gmail.com
	 *
	 * @param message
	 */
	public static Message insertMessage(String text) {
		if( log.isDebugEnabled() ) {
			log.debug( "insertMessage:INI" );
			log.debug( "text:" + text );
		}
		
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();

        Message message = new Message( text );
        session.save(message);

        tx.commit();
        session.close();

		if( log.isDebugEnabled() ) {
			log.debug( "message:" + message );
			log.debug( "insertMessage:END" );
		}
		
		return message;
	}
	
	public static List getAll() {
		if( log.isDebugEnabled() ) {
			log.debug( "getAll:INI" );
		}

		log.debug( "abrimos conexion..." );
        Session session = HibernateUtil.getSessionFactory().openSession();
        log.debug( "session:" + session );
        Transaction transaction = session.beginTransaction();

        List result =
            session.createQuery("from Message m").list();

        transaction.commit();
        session.close();
		
		if( log.isDebugEnabled() ) {
			log.debug( "result:" + result );
			log.debug( "getAll:END" );
		}
		
		return result;
	}
	
	public static void removeMessageById(Long id) {
		if( log.isDebugEnabled() ) {
			log.debug( "removeMessageById:INI" );
			log.debug( "id:" + id );
		}
		
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();

        Message message =
        	(Message)
        	session.get( Message.class, id );
        
        session.delete( message );
        
        tx.commit();
        session.close();
		
		if( log.isDebugEnabled() ) {
			log.debug( "removeMessageById:END" );
		}
	}
}
